<template>


	<view class=" main-bgH   ">
		<navigationBar></navigationBar>
		<!-- 		<image mode="widthFix" style="width: 200rpx;height: auto;left: 50rpx;" class="abs" src="@/static/logo.png"> -->
		</image>
		<view class=" flex  fd-c ai-c">
			<view class="fw-400" style="font-size: 60rpx;color: #242021;width: 504rpx;">
				向未来比个烨</view>

			<view class="" style="width: 80rpx;background-color: #000;height: 4rpx;margin-top: 26rpx;">
			</view>
			<!-- <image class="" style="width: 245rpx;" mode="widthFix"
				src="https://data-h5.oss-cn-shenzhen.aliyuncs.com/yang/2025/0311/btsh/xwl.png"> -->


			<view class="rel" style=" margin-top: 200rpx;">
				<image class="" style="width: 556rpx; " mode="widthFix" @click="tohd2"
					src="https://data-h5.oss-cn-shenzhen.aliyuncs.com/yang/2025/0311/btsh/f1.png">




					<view class=" abs fw-400 w-100"
						style="text-align: center;line-height: 55rpx;color: #333333;letter-spacing: 2rpx; bottom: 120rpx;font-size: 27rpx; font-family: 'SourceHanSans';">

						<!-- 	<view class="fs-28 m-b-10" style="color: #231815;font-weight: 500;">
								玩法说明
							</view> -->
						根据指引完成区域互动 <br>
						拍照合影<br>
						点亮1闪耀值<br>

					</view>
			</view>

		</view>


		<!-- <view @click="toggleStream" mode="widthFix"
			style="width: 322rpx;height: 67rpx; bottom: 20vh;border-radius: 7rpx; line-height: 67rpx;letter-spacing: 4rpx;"
			class="abs-x bg-fff">{{streaming ? '停止':'测试开始拍照'}}</view> -->
		<view @click="scanQRCode" mode="widthFix"
			style="width: 301rpx;height: 94rpx; bottom: 9vh;border-radius: 47rpx; line-height: 94rpx;letter-spacing: 4rpx; color: #465A7E;"
			class="abs-x bg-fff">{{streaming ? '停止':'扫码开启相机'}}</view>



		<FakeProgress :visible.sync="showProgress" :isDone="syntheticDone" @cancel="handleProgressCancel"
			@finishProgress="finishProgressRes">

			<text>拍摄完成，请耐心稍等片刻 <br /> 正在努力为您制作精美照片，即将呈现</text>


		</FakeProgress>

		<pop :visible.sync="popshow" :maskClickClose="false">

			<view class="countdownBJ">
				{{countdown}}
			</view>
			<view class="c-fff " style="padding-top: 188rpx;">面向镜头 保持微笑</view>
		</pop>

		<pop :visible.sync="popshow2" :maskClickClose="true">

		<view class="bg-fff c-000"
			style="width: 84vw;height: 54vw; border-radius: 10rpx; ">
			<view class="fw-b " style="font-size: 5.5vw;letter-spacing: 1vw;padding-top:6vw; ">
				活动登录
			</view>
			<view class="fs-30 " style="font-weight: 300;font-size: 4vw;letter-spacing:0.2vw;margin-top:7.5vw;white-space: nowrap;">
				继续参与活动需要登录授权
			</view>
		
			<view class="f jc-b ai-c"  style="width:68vw;margin: auto;margin-top:12vw;">
				<view @click="fanhui"
					style="width: 45%;height: 8vw;line-height: 8vw;font-size:4vw; font-weight: normal;border-radius:10vw;box-sizing: border-box; display: inline-flex; letter-spacing: 1px;background: #739AEF;color: #eee;"
					class="jc-c ai-c">前往授权</view>
				<view @click="popshowTap"
					style="width: 45%;height: 8vw;line-height: 8vw;font-size:4vw; font-weight: normal;border-radius:10vw;box-sizing: border-box; display: inline-flex; letter-spacing: 1px;background: #fff;color: #CCCCCC;border: 1px solid #D6D6D6;"
					class="jc-c ai-c">暂不登录</view>
			</view>
		</view>
		


		</pop>



	</view>


	<!-- 	<view class="container">
		<button @click="toggleStream">{{ streaming ? '停止监听' : '开始报名' }}</button>
		<view class="status-box">
			<text>当前状态：{{ statusText }}</text>
			<text >倒计时剩余：<text style="font-size: 250px;">{{ countdown }}</text> 秒</text>
			<text>游戏ID：{{ gameId }}</text>
			<image :src="getphotoUrl" mode="widthFix" style="width: 80vw;"></image>
		</view>
	</view> -->



</template>

<script>
	const wx = require('jweixin-module');

	import FakeProgress from "@/components/FakeProgress.vue"
	import pop from "@/components/pop.vue"
	import navigationBar from "@/components/navigationBar.vue"

	// 互动2正式页面  end 加上 倒计时
	// 流式接口地址
	const reqUrl = "https://platform.easys.co/hondaapi"
	// const reqUrl = "http://192.168.1.30:9000"



	export default {
		data() {
			return {
				OpenID: "",
				streaming: false,
				statusText: '等待连接',
				gameId: "",
				controller: null,
				buffer: '',
				countdown: 0,
				countdownTimer: null,
				serverStartTime: 0,


				getphotoUrl: "", //getphotoUrl
				timegetphoto: null,
				timestartStream: null,


				showProgress: false,
				syntheticDone: false,

				// popshow: true,
				popshow: false,
				popshow2: false,
				wxConfigLoaded: false,

			}
		},
		components: {
			"FakeProgress": FakeProgress,
			"pop": pop,
			"navigationBar": navigationBar,
		},
		onLoad() {

			// ！！！！ 正式环境要打开
			// this.$wx.initgetOpenId(function(res) {
			// 	console.log(res)
			// 	if(res.code == '200'){
			// 		OpenID = res.data.data.openid
			// 	}else{
			// 		uni.showToast({
			// 			title: "接口出错",
			// 			icon: 'none'
			// 		})
			// 	}
			// })
		},
		onShow() {


			// let user = this.getUrlParam("user") ? this.getUrlParam("user") : uni.getStorageSync('openid')
			
			
			let user = this.getUrlParam("user") ? this.getUrlParam("user") : ""
			console.log(user)
			console.log(this.getUrlParam("user"))
			if (user!= "") {

				uni.setStorageSync('openid', user);

				this.checkIn()

			} else {
					// this.popshow2 = true
				// uni.showModal({
				// 	title: "用户编码为空"
				// })
			}
			console.log(user)

		},
		methods: {
			popshowTap() {
				this.popshow2 = false
			},
			fanhui() {
				console.log("123")
				wx.miniProgram.navigateTo({
					url: "/pages/new/actRule/index"
				});
			},
			
			checkIn() {
				let param = {
					openid: uni.getStorageSync('openid')
				}
				this.$http.get('/TakePhoto/checkIn', param, res => {
					console.log(res)

					uni.setStorageSync('checkIn', res.data);
				})
			},

			//获取地址栏的参数
			getUrlParam(name) {

				console.log(window.location.href)


				var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
				var r = window.location.search.substr(1).match(reg);
				if (r != null) return unescape(r[2]);
				return null;
			},
			finishProgressRes() {
				this.handleProgressCancel()
				// 进度条结束了
				uni.navigateTo({
					url: "/pages/index_2_yb/index_2_yb?diyImg=" + this.getphotoUrl
				})
			},
			handleProgressCancel() {
				this.showProgress = false
				this.syntheticDone = false
			},

			scanQRCode() {
				
				let user = this.getUrlParam("user") ? this.getUrlParam("user") : ""
				console.log("user++++=" +user)
				console.log(user)
				if (user == "") {

					this.popshow2 = true
					
					return
				} 
				
				
				// this.toggleStream()

				this.$wx.scanQRCode((res) => {
					console.log(res)
					console.log(res.resultStr)

					if (res.resultStr && res.resultStr.includes("honda2025SHxpifqdx5yxe1xkwp93")) {
						this.toggleStream()
					} else {
						uni.showToast({
							title: "二维码错误",
							icon: 'none'
						})
					}
				})



			},
			getphoto() {



				if (!uni.getStorageSync('openid') && this.gameId == '') {
					uni.showToast({
						title: "网络繁忙",
						icon: 'none'
					})

					return
				}


				uni.request({
					// url: reqUrl + "/api/TakePhoto/getphoto?OpenID="+OpenID + '&GameID='+this.gameId,
					url: reqUrl + "/TakePhoto/getphoto?OpenID=" + uni.getStorageSync('openid') + '&gameId=' + this
						.gameId,
					success: (res) => {
						console.log(res);

						if (res.data.code == 200) {

							this.syntheticDone = true
							this.getphotoUrl = res.data.data;



						} else {

							this.timegetphoto = setTimeout(() => {
								this.getphoto(); //调用动画--滑入
								clearTimeout(this.timegetphoto);
								this.timegetphoto = null;
							}, 500)

						}


					},
					fail: (res) => {
						uni.showToast({
							title: "接口出错",
							icon: 'none'
						})
					}
				})
			},


			async toggleStream() {
				if (this.streaming) {
					this.stopStream()
				} else {
					await this.startStream()
				}
			},

			async startStream() {
				uni.showLoading({
					title: '加载中'
				})
				try {
					this.initState()
					this.controller = new AbortController()

					const response = await fetch(reqUrl + '/TakePhoto/tpcreate?openid=' + uni.getStorageSync(
						'openid'), {
						method: 'GET',
						headers: {
							'Content-Type': 'application/json'
						},
						// body: JSON.stringify({ /* 你的请求参数 */ }),
						signal: this.controller.signal
					})

					await this.processStream(response)
				} catch (error) {
					this.handleError(error)
				}
			},

			// 初始化状态
			initState() {
				uni.showLoading({
					title: '加载中'
				})


				this.streaming = true
				this.statusText = '连接服务中...'
				if (uni.getStorageSync("gameId")) {
					this.gameId = uni.getStorageSync("gameId")
				}

				this.buffer = ''
			},

			// 处理数据流
			async processStream(response) {
				if (!response.ok) throw new Error(`HTTP错误 ${response.status}`)
				if (!response.body) throw new Error('无响应内容')

				const reader = response.body.getReader()
				const decoder = new TextDecoder('utf-8')

				while (this.streaming) {
					const {
						done,
						value
					} = await reader.read()
					if (done) break

					// 处理数据块
					this.buffer += decoder.decode(value, {
						stream: true
					})
					console.log("接口原始输出= " + this.buffer);

					// // 微信环境下需要强制更新视图
					// this.$forceUpdate()

					this.processBuffer()
				}
			},

			// 处理缓冲区数据
			processBuffer() {
				while (true) {
					// 定位数据块起始和结束位置
					const startIdx = this.buffer.indexOf('[DONE]')
					const endIdx = this.buffer.indexOf('[END]')

					// 需要至少找到一个完整数据块
					if (startIdx === -1 || endIdx === -1 || endIdx < startIdx) return

					// 提取有效数据部分
					const chunk = this.buffer.slice(
						startIdx + 6, // '[DONE]' 长度6
						endIdx
					)

					// 更新缓冲区（保留未处理部分）
					this.buffer = this.buffer.slice(endIdx + 5) // '[END]' 长度5
					// console.log("更新缓冲区（保留未处理部分-正常为空）= "+this.buffer);

					// console.log("处理数据包= "+chunk);
					// 解析数据
					const params = this.parseChunk(chunk)
					this.handleParams(params)
				}
			},

			// 解析数据块
			parseChunk(chunk) {
				const params = new URLSearchParams(chunk)
				const result = {
					code: parseInt(params.get('code')),
					msg: params.get('msg'),
					gameId: params.get('GameID')
				}

				// 仅当code=202时解析时间参数
				if (result.code === 202) {
					result.starttime = parseInt(params.get('starttime')) || 0
					result.countdown = parseInt(params.get('Countdown')) || 0
				}
				return result
			},

			// 处理解析后的参数
			handleParams({
				code,
				msg,
				gameId,
				starttime,
				countdown
			}) {
				switch (code) {
					case 200:
						this.showProgress = true
						this.statusText = `✅ ${msg}`
						this.stopStream()
						this.getphoto()
						break
					case 201:
						uni.showLoading({
							title: '加载中'
						})
						this.statusText = `✅ ${msg}`
						this.gameId = gameId
						uni.setStorageSync("gameId", gameId)

						break
					case 202:
						uni.hideLoading()
						this.statusText = `📸 ${msg}`
						// this.gameId = gameId
						this.startCountdown(starttime, countdown)
						break
					case 4001:
					case 4002:
					case 4003:
					case 4004:
					case 40005:
						uni.showToast({
							title: "请求出错",
							icon: "error",
							duration: 2000,
						});
						uni.hideLoading()
						this.statusText = `${msg}`
						this.stopStream()
						uni.showToast({
							title: this.statusText,
							icon: "error",
							duration: 2000,
						});
						break
					default:
						uni.showToast({
							title: "请求出错",
							icon: "error",
							duration: 2000,
						});
						uni.hideLoading()
						this.statusText = `${msg}`
						this.stopStream()

				}

				this.$forceUpdate()
			},
			// 启动倒计时
			startCountdown(serverStartTime, totalSeconds) {
				// 清除已有定时器
				if (this.countdownTimer) clearInterval(this.countdownTimer)

				// 计算剩余时间（服务器时间 + 总秒数 - 当前时间）
				console.log(new Date(serverStartTime))

				// console.log((totalSeconds * 1000))

				const endTime = serverStartTime + (totalSeconds * 1000)
				const updateCountdown = () => {
					const remaining = Math.max(0, Math.round((endTime - Date.now()) / 1000))

					console.log(new Date(Date.now()))

					this.countdown = remaining


					console.log(remaining)

					if (remaining <= 0) {
						clearInterval(this.countdownTimer)
						this.countdown = 0

					}
					this.$forceUpdate()
				}

				// 立即执行一次并启动定时器
				this.popshow = true
				updateCountdown()
				this.countdownTimer = setInterval(updateCountdown, 1000)
			},

			// 停止流式传输（添加倒计时清理）
			stopStream() {
				if (this.controller) {
					this.controller.abort()
					this.controller = null
				}
				if (this.countdownTimer) {
					clearInterval(this.countdownTimer)
					this.countdownTimer = null
					this.countdown = 0
					this.popshow = false
					this.$forceUpdate()
				}
				this.streaming = false
				this.buffer = ''
			},


			// 错误处理
			handleError(error) {
				if (error.name === 'AbortError') {
					this.statusText = '⏹ 已手动停止'
				} else {


					this.timestartStream = setTimeout(() => {
						this.stopStream(); //调用动画--滑入
						this.startStream(); //调用动画--滑入
						clearTimeout(this.timestartStream);
						this.timestartStream = null;
					}, 500)



					console.log('请求失败:', error)
					this.statusText = `❌ 错误: ${error.message}`
				}
				this.$forceUpdate()
			}
		}
	}
</script>

<style>
	/* 	.main-bgH {
		width: 100%;
		height: 100%;
		padding: 12vh 50rpx 0;
		position: relative;
		background: url('https://data-h5.oss-cn-shenzhen.aliyuncs.com/yang/2025/0311/btsh/bj1.png');
		background-repeat: no-repeat;
		background-size: 100% 100%;
	} */

	.countdownBJ {
		width: 293rpx;
		height: 293rpx;
		line-height: 293rpx;
		background: url('https://data-h5.oss-cn-shenzhen.aliyuncs.com/yang/2025/0311/btsh/djs.png');
		background-repeat: no-repeat;
		background-size: 100% 100%;
		font-size: 240rpx;
		color: #ffffff;

	}

	.container {
		padding: 20px;
	}

	button {
		background-color: #07c160;
		color: white;
		padding: 15px 30px;
		border-radius: 25px;
		font-size: 16px;
	}

	.status-box {
		margin-top: 20px;
		padding: 15px;
		background-color: #f7f7f7;
		border-radius: 10px;
	}

	.status-box text {
		display: block;
		margin: 8px 0;
		font-size: 14px;
		color: #333;
	}

	.status-box text:nth-child(2) {
		color: #eb4d4b;
		font-weight: bold;
	}
</style>